<template>
  <div id="viewQuestionView">
    <a-row :gutter="[24, 24]">
      <a-col :md="12" :xs="24">
        <a-tabs default-active-key="question">
          <div style="text-align: center">
            <a-spin dot :hide-icon="!isLoading" />
          </div>
          <a-tab-pane key="question" title="题目">
            <a-card v-if="question" :title="question.title">
              <a-descriptions
                title="判题条件"
                :column="{ xs: 1, md: 2, lg: 3 }"
              >
                <a-descriptions-item label="时间限制">
                  {{ question.judgeConfig.timeLimit ?? 0 }}
                </a-descriptions-item>
                <a-descriptions-item label="内存限制">
                  {{ question.judgeConfig.memoryLimit ?? 0 }}
                </a-descriptions-item>
                <a-descriptions-item label="堆栈限制">
                  {{ question.judgeConfig.stackLimit ?? 0 }}
                </a-descriptions-item>
              </a-descriptions>
              <MdViewer :value="question.content || ''" />
              <template #extra>
                <a-space wrap>
                  <a-tag
                    v-for="(tag, index) of question.tags"
                    :key="index"
                    color="green"
                    >{{ tag }}
                  </a-tag>
                </a-space>
              </template>
            </a-card>
          </a-tab-pane>
          <a-tab-pane key="comment" title="评论">
            <div>
              <a-comment align="right" :avatar="userAvatar">
                <template #actions>
                  <a-button
                    v-if="replyStatus == true"
                    key="0"
                    type="secondary"
                    @click="cancelReply"
                    >取消回复
                  </a-button>
                  <a-button key="1" type="primary" @click="doComment"
                    >点击评论
                  </a-button>
                </template>
                <template #content>
                  <a-textarea
                    :placeholder="placeholder"
                    allow-clear
                    v-model="commentContent"
                  />
                </template>
              </a-comment>
            </div>
            <div v-for="(item, index) of commentDataList" :key="index">
              <a-comment
                :author="item.userVO.userName"
                :avatar="item.userVO.userAvatar"
                :content="item.content"
                :datetime="moment(item.createTime).format(' MM-DD HH:mm:ss')"
              >
                <!--                <template #actions>-->
                <!--                  <span class="action" @click="reply(item)">-->
                <!--                    <IconMessage /> 回复-->
                <!--                  </span>-->
                <!--                  <div style="padding-top: 13px">-->
                <!--                    <a-popconfirm content="确认修改？" @ok="remove(item)">-->
                <!--                      <a-button type="outline" status="danger" size="mini"-->
                <!--                        >删除-->
                <!--                      </a-button>-->
                <!--                    </a-popconfirm>-->
                <!--                  </div>-->
                <!--                </template>-->
                <div
                  v-for="(replyItem, replyIndex) of replyDataList"
                  :key="replyIndex"
                >
                  <div v-if="item.hasReplies == true">
                    <div>
                      <a-comment
                        :author="`${replyItem.userVO.userName} ${'回复'} ${
                          replyItem.replyUserName
                        }`"
                        :avatar="replyItem.userVO.userAvatar"
                        :content="replyItem.content"
                        :datetime="
                          moment(replyItem.createTime).format(' MM-DD HH:mm:ss')
                        "
                      >
                        <template #actions>
                          <span class="action" @click="reply(replyItem)">
                            <IconMessage /> 回复
                          </span>
                        </template>
                      </a-comment>
                    </div>
                  </div>
                </div>
              </a-comment>
            </div>
          </a-tab-pane>
          <a-tab-pane key="answer" title="答案">
            <CodeAnswerEditor
              :value="answer"
              :language="form.language"
              :handle-change="changeCode"
              :key="key"
            />
          </a-tab-pane>
        </a-tabs>
      </a-col>
      <a-col :md="12" :xs="24">
        <a-form :model="form" layout="inline">
          <a-form-item
            field="language"
            label="编程语言"
            style="min-width: 240px"
          >
            <a-select
              v-model="form.language"
              :style="{ width: '100px' }"
              placeholder="选择编程语言"
            >
              <a-option>java</a-option>
              <a-option>cpp</a-option>
              <a-option>go</a-option>
              <a-option>html</a-option>
            </a-select>
          </a-form-item>
          <a-button type="primary" @click="doSubmit" :loading="!loadingButton">
            提交代码
          </a-button>
        </a-form>
        <a-divider size="0" />
        <CodeEditor
          :value="form.code as string"
          :language="form.language"
          :handle-change="changeCode"
          :key="key"
        />
      </a-col>
    </a-row>
  </div>
</template>

<script setup lang="ts">
import { defineProps, onMounted, ref, withDefaults } from "vue";
import {
  QuestionControllerService,
  QuestionSubmitAddRequest,
  QuestionVO,
} from "../../../generated";
import message from "@arco-design/web-vue/es/message";
import CodeEditor from "@/components/CodeEditor.vue";
import MdViewer from "@/components/MdViewer.vue";
import CodeAnswerEditor from "@/components/CodeAnswerEditor.vue";
import { CommentControllerService } from "../../../generated/services/CommentControllerService";
import moment from "moment/moment";

interface Props {
  id: string;
}

const userAvatar = ref("");
const replyStatus = ref(false);
const placeholder = ref("请输入评论内容");
const commentContent = ref("");
const loadingButton = ref(true);
const isLoading = ref(true);
const answer = ref("");
const theme = ref("vs");
const key = ref(0);
const props = withDefaults(defineProps<Props>(), {
  id: () => "",
});

const question = ref<QuestionVO>();
const tempData = ref();
const commentDataList = ref([]);
const replyDataList = ref([]);
const loadData = async () => {
  const res = await QuestionControllerService.getQuestionVoByIdUsingGet(
    props.id as any
  );
  const data = {
    questionId: props.id,
  };
  const resp = await QuestionControllerService.getMyCodeUsingPost(data);
  //加载评论数据
  const commentRes =
    await CommentControllerService.listCommentVoByPageUsingPost({
      current: 0,
      pageSize: 20,
      questionId: props.id,
    });
  if (res.code === 0) {
    isLoading.value = false;
    question.value = res.data;
  } else {
    message.error("加载失败，" + res.message);
    isLoading.value = false;
  }
  //加载该题目的答案
  const answerResp = await QuestionControllerService.getQuestionAnswerUsingGet(
    props.id as any
  );
  //加载评论
  commentDataList.value = commentRes.data?.records;
  answer.value = answerResp.data;
  //判断是否存在子评论
  // for (let i = 0; i < commentDataList.value.length; i++) {
  //   console.log(commentDataList.value[i].id);
  //   const replyRes = await ReplyControllerService.listReplyVoByPageUsingPost({
  //     current: 0,
  //     pageSize: 10,
  //     commentId: commentDataList.value[i].id,
  //   });
  //   console.log(replyRes.data);
  //   if (replyRes.data?.records.length !== 0) {
  //     replyDataList.value = replyRes.data?.records;
  //     commentDataList.value[i]["hasReplies"] = true;
  //     console.log("replyDataList", replyDataList.value);
  //   }
  // }
  changeCode(resp.data as string);
  key.value++;
};

const doComment = async () => {
  console.log("dada", commentContent.value);
  const commentRes = await CommentControllerService.addCommentUsingPost({
    content: commentContent.value,
    questionId: props.id as any,
  });
  if (commentRes.code === 0) {
    message.success("评论成功");
    loadData();
  } else {
    message.error("发表评论失败");
  }
  commentContent.value = null;
};
const reply = (data) => {
  placeholder.value = "回复" + data.userVO.userName;
  replyStatus.value = true;
};
const form = ref<QuestionSubmitAddRequest>({
  language: "java",
  code: "",
});

const cancelReply = () => {
  replyStatus.value = false;
  placeholder.value = "请输入评论内容";
};
/**
 * 提交代码
 */
const doSubmit = async () => {
  loadingButton.value = false;
  if (!question.value?.id) {
    return;
  }
  const res = await QuestionControllerService.doQuestionSubmitUsingPost({
    ...form.value,
    questionId: question.value.id,
  });
  if (res.code === 0) {
    message.success("提交成功");
    loadingButton.value = true;
  } else {
    message.error("提交失败," + res.message);
    loadingButton.value = true;
  }
};

const remove = async (item) => {
  const res = await CommentControllerService.deleteCommentUsingPost({
    id: item.id,
  });
  if (res.code === 0) {
    message.success("删除成功！");
  } else {
    message.error("删除失败");
  }
  loadData();
};
/**
 * 页面加载时，请求数据
 */
onMounted(() => {
  //获取用户头像
  userAvatar.value = localStorage.getItem("userAvatar");
  loadData();
});

const changeCode = (value: string) => {
  form.value.code = value;
};
</script>

<style>
#viewQuestionView {
  max-width: 1400px;
  margin: 0 auto;
}

#viewQuestionView .arco-space-horizontal .arco-space-item {
  margin-bottom: 0 !important;
}

.action {
  display: inline-block;
  padding: 0 4px;
  color: var(--color-text-1);
  line-height: 24px;
  background: transparent;
  border-radius: 2px;
  cursor: pointer;
  transition: all 0.1s ease;
}

.action:hover {
  background: var(--color-fill-3);
}
</style>
